package api

import (
	"fmt"
	"log"
	"net/http"
	"rbapi/models"

	"golang.org/x/crypto/bcrypt"

	"github.com/dchest/captcha"
	session "github.com/ipfans/echo-session"
	"github.com/labstack/echo"
)

// Login 登录页面
func Login(c echo.Context) error {
	// fmt.Printf("In Login")
	captchaID := captcha.NewLen(4)
	// fmt.Printf("captchaID is %s", captchaID)
	return c.Render(http.StatusOK, "login.html", map[string]interface{}{
		"captchaID": captchaID,
	})
}

// GetCaptcha 验证码
func GetCaptcha(c echo.Context) error {
	captcha.Server(captcha.StdWidth, captcha.StdHeight).ServeHTTP(c.Response(), c.Request())
	return c.NoContent(http.StatusOK)
}

// Logon 登录行为
func Logon(c echo.Context) error {
	sess := session.Default(c)
	username := c.FormValue("tx_username")
	password := c.FormValue("tx_password")
	captchavalue := c.FormValue("tx_captchavalue")
	captchaid := c.FormValue("tx_captchaid")
	if !captcha.VerifyString(captchaid, captchavalue) {
		return goLogin("您输入的验证码不正确，请重新输入", c)
	}
	var user models.User
	models.Mdb.First(&user, "name = ?", username)
	log.Print(username)
	log.Print(user)
	if user.ID != 0 {
		// h := sha1.New()
		// h.Write([]byte(password))
		// cp := hex.EncodeToString(h.Sum(nil))
		// op, err := hex.DecodeString(user.EncryptedPassword)
		// opp := string(op)
		// log.Print(cp)
		// log.Print(err)
		// log.Print(opp)
		fmt.Printf("===========>hashpassword is %s\n", user.PasswordDigest)
		fmt.Printf("===========>password is %s\n", password)
		result := bcrypt.CompareHashAndPassword([]byte(user.PasswordDigest), []byte(password))
		if result == nil {
			sess.Set("user_id", user.ID)
			userID := sess.Get("user_id")
			log.Print("user_id is ", userID)
			sess.Save()
			return c.Redirect(302, "/admin")
		}
		fmt.Printf("===========>password not right,%s\n", result.Error())
		return c.Redirect(302, "/login")
		// return goLogin("用户不存在或密码错误", c)
	}
	return c.Redirect(302, "/login")
	// return goLogin("用户不存在或密码错误", c)
}

func goLogin(errMsg string, c echo.Context) error {
	captchaID := captcha.NewLen(4)
	return c.Render(http.StatusUnauthorized, "login.html", map[string]interface{}{
		"captchaID": captchaID,
		"error":     errMsg,
	})
}

// Logout 注销登录
func Logout(c echo.Context) error {
	log.Print("in Logout")
	sess := session.Default(c)
	sess.Clear()
	sess.Save()
	log.Print("session has been clear,111111")
	return c.Redirect(302, "/login")
}

// GetAllUser 获得全部用户
// @Title Get User List
// @Description 获得全部用户
// @Success 200 {object[]} models.User[]
// @Failure 500 get users common error
// @router /get_all_user
func GetAllUser(c echo.Context) error {
	var users []models.User
	models.Mdb.Preload("Role").Preload("UserRoles").Preload("Role").Find(&users)
	result := struct {
		Success bool        `json:"success"`
		UserArr interface{} `json:"user_arr"`
	}{}
	result.Success = true
	result.UserArr = users
	return c.JSON(http.StatusOK, result)
}
